package app.models.basic;

import app.kit.CommonKit;
import app.kit.TypeKit;
import goja.annotation.TableBind;
import goja.date.DateFormatter;
import goja.plugins.sqlinxml.SqlKit;
import goja.rapid.db.Model;
import goja.tuples.Pair;
import org.joda.time.DateTime;

import java.util.List;

/**
 * <p>
 * The database rlb_notes Model.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
@TableBind(tableName = "rlb_msgs")
public class Msgs extends Model<Msgs> {

    /**
     * The public dao.
     */
    public static final Msgs dao = new Msgs();

    private static final long serialVersionUID = -7345393577600275467L;


    public static Msgs sendMsg(int memberId, String title, String content){
        Msgs msg = new Msgs();
        msg.set("type", 0);
        msg.set("title", title);
        msg.set("friend_id", memberId);
        msg.set("receiver", memberId);
        msg.set("send_time", DateTime.now());
        msg.set("content", content);
        msg.set("status", 0);
        return msg;
    }


    public List<Msgs> findByMember(int memberId, int page) {
        final Pair<Integer, Integer> offsets = CommonKit.pageOffset(page);
        return find(SqlKit.sql("msgs.findByMember"), memberId, offsets.getValue1(), offsets.getValue0());
    }
    public List<Msgs> findByMemberAndThreeMouth(int memberId, int page) {
        DateTime now = DateTime.now();
        final DateTime month_time = now.plusDays(-90);
        String lastT = month_time.toString(DateFormatter.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
        final Pair<Integer, Integer> offsets = CommonKit.pageOffset(page);
        return find(SqlKit.sql("msgs.findByMemberAndThreeMonth"), memberId, offsets.getValue1(), offsets.getValue0(),lastT);
    }
    public int findCountByMemberAndThreeMouth(int memberId) {
        DateTime now = DateTime.now();
        final DateTime month_time = now.plusDays(-90);
        String lastT = month_time.toString(DateFormatter.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
        return find(SqlKit.sql("msgs.findCountByMemberAndThreeMonth"), memberId,lastT).get(0).getBigDecimal("count").intValue();
    }

    public int findUnReadCountByMemberAndThreeMonth(int memberId) {
        DateTime now = DateTime.now();
        final DateTime month_time = now.plusDays(-90);
        String lastT = month_time.toString(DateFormatter.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
        return find(SqlKit.sql("msgs.findUnReadCountByMemberAndThreeMonth"), memberId,lastT).get(0).getBigDecimal("count").intValue();
    }

    public int findCountByUnreade(int member) {
        Msgs counts = findFirst(SqlKit.sql("msgs.findCountByUnreade"), member,0);
        if(counts == null){
            return 0;
        } else {
            return TypeKit.getInt(counts, "cnt");
        }
    }
}